<?php

class InstallController extends Zend_Controller_Action
{

    function init()
    {

    }
    function indexAction()
    {

    }
    function step1Action()
    {
        // Required extensions
        $extensions = array(
            'gd', 'json', 'mbstring',
            'mysql', 'pdo', 'pdo_mysql',
            'simplexml', 'xml', 'xmlreader',
        );
        $pass = true;
        $requiredExtensions = array();
        foreach ($extensions as $ext) {
            $requiredExtensions[$ext] = extension_loaded($ext);
            $pass = $pass && $requiredExtensions[$ext];
        }
        $this->view->assign('requiredExtensions', $requiredExtensions);

        // Files/folders must have writing permission
        $files = array(
            'application'.DIRECTORY_SEPARATOR.'configs'.DIRECTORY_SEPARATOR.'application.ini',
            'public'.DIRECTORY_SEPARATOR.'cache',
            'data',
            'cache',
        );
        $writableFiles = array();
        foreach ($files as $f) {
            $writableFiles[$f] = is_writeable(SFS_ROOT_DIR . DIRECTORY_SEPARATOR . $f);
            $pass = $pass && $writableFiles[$f];
        }
        $this->view->assign('writableFiles', $writableFiles);
        $this->view->assign('pass', $pass);

        if ($this->_request->isPost() && $pass) {
            $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'install_step2'));
        }
    }

    function step2Action()
    {

        $mode = $this->_request->getParam('mode', 'install');
        $this->view->assign('mode', $mode);
        $sections = array();

        $config = Sfs_Core_Config::getConfig();

        foreach ($config->toArray() as $section => $data) {
            $sections[$section] = $data;
        }

        /**
         *  Database
         */
        $dsnurl = $sections['production']['doctrine']['connection_string'];
        $master = parse_url($dsnurl);
        $master['dbname'] = substr($master['path'],1);
        if (isset($master['query'])) {
            $temp = explode('&',$master['query']);
            $options = array();
            foreach($temp as $val) {
                $temp2 = explode("=",$val);
                $options[$temp2[0]] = $temp2[1];
            }
            $master['port'] = $options['port'];
        }


        $this->view->master = $master;

        if ('saveConfig' == $mode || $this->_request->isPost()) {


            $file = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'configs'. DIRECTORY_SEPARATOR .'application.ini';
            $config = new Zend_Config_Ini($file, null, array('allowModifications' => true));
            $config = $config->toArray();


            $host = $this->_getParam('host');
            $port = $this->_getParam('port');
            $username = $this->_getParam('username');
            $password = $this->_getParam('password');
            $dbname = $this->_getParam('dbname');
            if ($port == '' or $port == 3306)
            $port = "";
            else
            $port = "?port=$port";

            $config['production']['doctrine']['connection_string']  = "mysql://$username:$password@$host/$dbname$port";
            //      $config['development']['doctrine']['connection_string']  = "mysql://$username:$password@$host/$dbname$port";
            // 寫入設定

            $writer = new Zend_Config_Writer_Ini();
            $writer->write($file, new Zend_Config($config));
            $ok = true;

            // 檢查資料庫是否存在
            $connect = @mysql_connect($host,$username,$password);
            if (!$connect) {
                $ok = false;
                //$this->_helper->getHelper('Messenger')
                //->addMessage($this->view->translate('install_step2_database_connect_error'));
                throw (new Exception('install_step2_database_host_error'));
            }
            try {
                // 檢查管理者密碼是否正確
                if ($this->_getParam('admin_password') != $this->_getParam('confirm_password')) {
//                    $this->_helper->getHelper('FlashMessenger')
//                    ->addMessage($this->view->translate('install_step2_password_not_match'));
                    throw (new Exception('password not match'));
                }
                if (!@mysql_select_db($dbname , $connect) ){
                    mysql_query("CREATE DATABASE $dbname");
                }
                require_once 'Doctrine.php';
                $loader = Zend_Loader_Autoloader::getInstance();
                $loader->pushAutoloader(array('Doctrine', 'autoload'));

                $manager = Doctrine_Manager::getInstance();

                $manager->setAttribute(Doctrine::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
                $manager->setAttribute(
                Doctrine::ATTR_MODEL_LOADING,
                Doctrine::MODEL_LOADING_CONSERVATIVE);
                $manager->setAttribute(Doctrine::ATTR_AUTOLOAD_TABLE_CLASSES,true);


                // Add models and generated base classes to Doctrine autoloader
                $conn = $manager->openConnection($config['production']['doctrine']['connection_string']);
                if ($conn)
                $conn->setCharset('utf8');
                $conn->setAttribute(Doctrine::ATTR_USE_NATIVE_ENUM, true);
                $res = $conn->execute('SHOW TABLES')->fetch();

                if ($res) {
                    $ok = false;
                    $this->_helper->getHelper('FlashMessenger')
                    ->addMessage(sprintf($this->view->translate('install_step2_database_has_data %s'), $dbname));
                    throw (new Exception('install_step2_database_has_data'));
                } else {
                    $sqlFile  = APPLICATION_PATH.'/doctrine/data/zfsfs.sql';
                    Sfs_Core_Services_Install_Importer::import($sqlFile , $config['production']['doctrine']['connection_string'])   ;


                    // 建立 第一個 user
                    $username = trim($this->_getParam('admin_user'));
                    // TODO 原 SFS3 md5 問題 待修正
                    $pass = md5(trim($this->_getParam('admin_password')));
                    $password = substr($pass,10).substr($pass,0,9);

                    $email = trim($this->_getParam('admin_email'));
                    $conn->execute("INSERT INTO users (name,username,password,email)
                        VALUES('Adminstrator','$username','$password','$email')");
                    $conn->execute("INSERT INTO groups (role_id,username)
                    VALUES('Administrator','$username')");

                    //TODO 建立 Doctrine YAML 資料表
                }

            } catch(Exception $e) {

                $ok = false;
            }
            if ($ok) {

                $this->_forward('step3');
                $config['production']['install']['version'] = '5.0';
                $config['production']['install']['date'] = date ("Y-m-d",time());
                $writer = new Zend_Config_Writer_Ini();
                $writer->write($file, new Zend_Config($config));
            } else {
                $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'install_step2'));
            }
        }


    }

    function step3Action()
    {

    }

    public function errorAction()
    {

        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

                // 404 error -- controller or action not found
                $this->getResponse()->setHttpResponseCode(404);
                $this->view->message = 'Page not found';
                break;
            default:
                // application error
                $this->getResponse()->setHttpResponseCode(500);
                $this->view->message = 'Application error';
                break;
        }

        $this->view->exception = $errors->exception;
        $this->view->request   = $errors->request;
    }

}
